<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="warehouseId">
        <treeselect v-model="queryParams.warehouseId" :options="warehouseOptions" :show-count="true" placeholder="仓库"
          style="width: 120px" />
      </el-form-item>
      <el-form-item prop="vendorId">
        <treeselect v-model="queryParams.vendorId" :options="vendorOptions" :show-count="true" placeholder="供应商"
          style="width: 190px" />
      </el-form-item>
      <el-form-item label="收货时间" prop="receiptTime">
        <el-date-picker clearable v-model="queryParams.receiptTime" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="receiptStatus">
        <el-select v-model="queryParams.receiptStatus" placeholder="收货状态" clearable>
          <el-option v-for="dict in dict.type.tb_receipt" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="unknown">
        <el-input placeholder="搜索内容" v-model="queryParams.unknown" class="input-with-select"
          :style="{ width: '350px' }">
          <el-select v-model="select" slot="prepend" placeholder="请选择" :style="{ width: '100px' }">
            <el-option label="收货单号" value="1"></el-option>
            <el-option label="采购员" value="2"></el-option>
            <el-option label="收货人" value="3"></el-option>
            <el-option label="品名" value="4"></el-option>
            <el-option label="SKU" value="5"></el-option>
            <el-option label="备注" value="6"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['depot:receipt:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['depot:receipt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['depot:receipt:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['depot:receipt:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['depot:receipt:add']"
          @click="handleBatchAdd">
          批量收货
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" :disabled="!batchQualityEnabled"
          @click="batchQualityInspection" v-hasPermi="['depot:receipt:quality']">批量质检</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" width="20" type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.DTOReceiptProductsList || []" :receipt-status="scope.row.receiptStatus">
            <el-table-column label="图片 " prop="imgName" align="center" min-width="50">
              <template slot-scope="scope">
                <!-- <image-preview :src="scope.row.img_name" :width="50" :height="50" /> -->
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </template>
            </el-table-column>
            <el-table-column label="品名" prop="productName" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="SKU" align="center" prop="sku" min-width="80">
            </el-table-column>
            <!-- 新增 GTIN 列 -->
            <el-table-column label="GTIN" align="center" min-width="120">
              <template slot-scope="childScope">
                <div v-if="childScope.row.gtins && childScope.row.gtins.length">
                  <div v-for="(gtin, index) in childScope.row.gtins" :key="index">{{ gtin }}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="通知收货量" prop="notificationQuantity" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="收货量" prop="receiptQuantity" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="收货差异" align="center" min-width="80">
              <template slot-scope="childScope">
                <span :style="{ color: scope.row.receiptStatus == 1 ? getDifferenceColor(childScope.row) : 'black' }">
                  {{ scope.row.receiptStatus == 1 ? formatDifference(childScope.row) : '-' }}
                </span>
              </template>
            </el-table-column>

            <!-- <el-table-column label="待检量" prop="pendingQuantity" align="center">
            </el-table-column> -->
            <el-table-column label="未检量" prop="notInspected" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="质检中" prop="qualityInspection" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="已检量" prop="checkedQuantity" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="可用量" prop="availableQuantity" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="次品量" prop="defectiveQuantity" align="center" min-width="80">
            </el-table-column>
            <el-table-column label="质检状态" align="center" prop="qualityStatus" min-width="100">
              <template slot-scope="childScope">
                <dict-tag :options="dict.type.tb_quality_inspection_status" :value="childScope.row.qualityStatus" />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="收货编号" align="center" prop="receiptNumber" />
      <el-table-column label="关联单据号" align="center" prop="ordersNumber" width="150" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="供应商" align="center" prop="name" />
      <el-table-column label="通知收货量" align="center" prop="noticeReceiptQuantity" />
      <el-table-column label="收货量" align="center" prop="receiptQuantity" />
      <el-table-column label="收货人" align="center" prop="consignee" />
      <el-table-column label="收货时间" align="center" prop="receiptTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.receiptTime ? parseTime(scope.row.receiptTime, "{y}-{m}-{d}") : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="收货状态" align="center" prop="receiptStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_receipt" :value="scope.row.receiptStatus" />
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="receiptRemark">
        <template slot-scope="scope">
          <span :title="scope.row.receiptRemark" class="text-ellipsis">{{ scope.row.receiptRemark ?
            scope.row.receiptRemark : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
            'depot:receipt:edit',
            'depot:receipt:remove',
            'depot:receipt:receive',
          ]">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleUpdate" icon="el-icon-edit" v-hasPermi="['depot:receipt:edit']"
                v-if="scope.row.receiptStatus == 0">修改</el-dropdown-item>
              <el-dropdown-item command="handleDelete" icon="el-icon-delete" v-hasPermi="['depot:receipt:remove']"
                v-if="scope.row.receiptStatus == 0">删除</el-dropdown-item>
              <el-dropdown-item command="handleReceived" icon="el-icon-document-checked"
                v-hasPermi="['depot:receipt:receive']" v-if="scope.row.receiptStatus == 0">收货</el-dropdown-item>
              <el-dropdown-item command="handleQualityCheck" icon="el-icon-s-check"
                v-hasPermi="['depot:receipt:quality']" v-if="scope.row.receiptStatus == 1">质检</el-dropdown-item>
              <el-dropdown-item command="handleExemptCheck" icon="el-icon-s-help" v-hasPermi="['depot:receipt:exempt']"
                v-if="scope.row.receiptStatus == 1">免检</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加收货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收货仓库" prop="warehouseId">
              <treeselect v-model="form.warehouseId" :options="warehouseOptions" :show-count="true" placeholder="仓库"
                @input="updateWarehouseContent" />
            </el-form-item>
            <el-form-item label="到货时间" prop="receiptTime">
              <el-date-picker clearable v-model="form.receiptTime" type="date" value-format="yyyy-MM-dd"
                style="width: 275px" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单据号" prop="ordersId">
              <treeselect v-model="form.ordersId" :options="procuredOrdersOptions" :show-count="true"
                :allow-create="true" :disabled="hasWarehouseContent" placeholder="订单编号" @input="checkOpenDialog"
                :loading="loading" />
            </el-form-item>
            <el-form-item label="运费" prop="freight">
              <el-input v-model="form.freight" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="name">
              <el-input v-model="form.name" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购人员" prop="userName">
              <el-input v-model="form.userName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="receiptRemark">
          <el-input v-model="form.receiptRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">收货单信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddReceiptProducts">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteReceiptProducts">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="DTOReceiptProductsList" :row-class-name="rowReceiptProductsIndex"
          @selection-change="handleReceiptProductsSelectionChange" ref="DTOReceiptProducts" height="700px"
          @select="handleReceiptProductSelect" :span-method="tableSpanMethod">
          <el-table-column type="selection" align="center" />
          <el-table-column label="图片" prop="imgName" align="center" min-width="100">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="产品编号" align="center" prop="productProNo" />
          <el-table-column label="品名/SKU" align="center" prop="sku">
            <template slot-scope="scope">
              {{ scope.row.productName }}<br />{{ scope.row.sku }}
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" prop="gtin" />
          <!-- 采购量（汇总） -->
          <el-table-column label="采购量" align="center" prop="transferableNumber">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                {{ skuGroupInfo[scope.row.sku].sumTransferableNumber }}
              </span>
            </template>
          </el-table-column>

          <!-- 待到货量（汇总） -->
          <el-table-column label="待到货量" align="center" prop="waitingStock">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                {{ skuGroupInfo[scope.row.sku].sumWaitingStock }}
              </span>
            </template>
          </el-table-column>

          <!-- 已通知量（汇总） -->
          <el-table-column label="已通知量" align="center" prop="notifiedCount">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                {{ skuGroupInfo[scope.row.sku].sumNotifiedCount }}
              </span>
            </template>
          </el-table-column>

          <!-- 未通知量（汇总） -->
          <el-table-column label="未通知量" align="center" prop="unnotifiedQuantity">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                {{ skuGroupInfo[scope.row.sku].sumUnnotifiedQuantity }}
              </span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="通知收货量" prop="notificationQuantity">
            <template slot-scope="scope">
              <el-input v-model="scope.row.notificationQuantity" placeholder="请输入通知收货量" :style="{ width: '100px' }" />
            </template>
          </el-table-column> -->
          <el-table-column label="合计通知收货量" prop="notificationQuantity">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center;">
                <!-- 计算合计的通知收货量 -->
                <el-input v-model="scope.row.notificationQuantity" placeholder="请输入通知收货量" :style="{ width: '100px' }" />
                <!-- 汇总整个SKU分组的未通知量 -->
                <el-tooltip v-if="isNotificationExceedGroup(scope.row.sku)" content="通知收货量大于未通知量，请确认是否要超量通知"
                  placement="top">
                  <i class="el-icon-info" style="color: #f56c6c; margin-left: 5px;"></i>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="detailsRemark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.detailsRemark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改收货单对话框 -->
    <el-dialog :title="updateTitle" :visible.sync="updateOpen" width="1600px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="form" :model="formUpdate" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收货仓库" prop="warehouseId">
              <treeselect v-model="formUpdate.warehouseId" :options="warehouseOptions" :show-count="true"
                placeholder="仓库" :disabled="true" />
            </el-form-item>
            <el-form-item label="预约到货时间" prop="receiptTime">
              <el-date-picker clearable v-model="formUpdate.receiptTime" type="date" value-format="yyyy-MM-dd"
                style="width: 275px" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单据号" prop="ordersNumber">
              <el-input v-model="formUpdate.ordersNumber" placeholder="订单编号" disabled />
            </el-form-item>

            <el-form-item label="运费" prop="receiptNumber">
              <el-input v-model="formUpdate.freight" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="name">
              <el-input v-model="formUpdate.name" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购人员" prop="userName">
              <el-input v-model="formUpdate.userName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="receiptRemark">
          <el-input v-model="formUpdate.receiptRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">收货单信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini"
              @click="handleUpdateReceiptProducts">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteReceiptProducts">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="DTOReceiptProductsList" :row-class-name="rowReceiptProductsIndex"
          @selection-change="handleReceiptProductsSelectionChange" ref="DTOReceiptProducts" height="700px"
          :span-method="tableSpanMethod">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="图片" prop="imgName" align="center" min-width="100">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="产品编号" align="center" prop="productProNo" />
          <el-table-column label="品名/SKU" align="center" prop="sku">
            <template slot-scope="scope">
              {{ scope.row.productName }}<br />{{ scope.row.sku }}
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" prop="gtin" />
          <el-table-column label="采购量" align="center" prop="transferableNumber">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupUpdateInfo[scope.row.sku].firstIndex">
                {{ skuGroupUpdateInfo[scope.row.sku].sumTransferableNumber }}
              </span>
            </template>
          </el-table-column>

          <!-- 待到货量（汇总） -->
          <el-table-column label="待到货量" align="center" prop="waitingStock">
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupUpdateInfo[scope.row.sku].firstIndex">
                {{ skuGroupUpdateInfo[scope.row.sku].sumWaitingStock }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="已通知量" align="center" prop="notifiedCount">
            <template slot="header">
              已通知量
              <el-tooltip content="已通知量=已通知未到货数量，统计“待收货”状态的收货单。注：编辑收货单时，不计算当前单据" placement="top">
                <!-- <el-icon> -->
                <i class="el-icon-info"></i>
                <!-- </el-icon> -->
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <span v-if="scope.$index === skuGroupUpdateInfo[scope.row.sku].firstIndex">
                {{ skuGroupUpdateInfo[scope.row.sku].sumNotifiedCount }}
              </span>
              <span v-else>0</span>
            </template>
          </el-table-column>

          <el-table-column label="未通知量" align="center" prop="unnotifiedQuantity">
            <template slot="header">
              未通知量
              <el-tooltip content="未通知量 = max(待到货量 - 已通知量, 0)" placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <!-- 只在分组首行显示汇总 -->
              <span v-if="scope.$index === skuGroupUpdateInfo[scope.row.sku].firstIndex">
                {{ Math.max(skuGroupUpdateInfo[scope.row.sku].sumWaitingStock -
                  skuGroupUpdateInfo[scope.row.sku].sumNotifiedCount,
                  0) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="合计通知收货量" prop="notificationQuantity">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center;">
                <template v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                  <!-- 计算合计的通知收货量 -->
                  <el-input v-model="scope.row.notificationQuantity" placeholder="请输入通知收货量"
                    :style="{ width: '100px' }" />
                  <!-- 汇总整个SKU分组的未通知量 -->
                  <el-tooltip v-if="scope.row.notificationQuantity > (Math.max(skuGroupUpdateInfo[scope.row.sku].sumWaitingStock - skuGroupUpdateInfo[scope.row.sku].sumNotifiedCount,
                    0))" content="通知收货量大于未通知量，请确认是否要超量通知" placement="top">
                    <i class="el-icon-info" style="color: #f56c6c; margin-left: 5px;"></i>
                  </el-tooltip>
                </template>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="合计通知收货量" prop="notificationQuantity">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center;">
                <template v-if="scope.$index === skuGroupInfo[scope.row.sku].firstIndex">
                  <el-input v-model="scope.row.notificationQuantity" placeholder="请输入通知收货量"
                    :style="{ width: '100px' }" />
                  <el-tooltip v-if="skuGroupInfo[scope.row.sku].sumNotificationQuantity > (Math.max(skuGroupInfo[scope.row.sku].sumWaitingStock - skuGroupInfo[scope.row.sku].sumNotifiedCount,
                    0))" content="通知收货量大于未通知量，请确认是否要超量通知" placement="top">
                    <i class="el-icon-info" style="color: #f56c6c; margin-left: 5px;"></i>
                  </el-tooltip>
                </template>
              </div>
            </template>
          </el-table-column> -->

          <el-table-column label="备注" prop="detailsRemark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.detailsRemark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormUpdate">确 定</el-button>
        <el-button @click="cancelUpdate(1)">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增收货单中选择更多来源单据号窗口 -->
    <el-dialog :title="orderIdTitle" :visible.sync="orderIdOpen" width="1600px" append-to-body
      :close-on-click-modal="false">
      <el-form :model="queryParamOrder" ref="queryForm" size="small" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="采购单号" prop="ordersNumber">
          <el-input v-model="queryParamOrder.ordersNumber" placeholder="请输入采购单号" clearable
            @keyup.enter.native="handleQueryProduct" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryProduct">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="ProcuredOrdersList" height="554px">
        <el-table-column label="采购单号" align="center" prop="ordersNumber" />
        <el-table-column label="采购计划号" align="center" prop="planNumber" />
        <el-table-column label="寄往仓库" align="center" prop="companyName">
          <template slot-scope="scope">
            <span v-if="scope.row.companyName">
              {{ scope.row.companyName.slice(0, 10) }}
              <span v-if="scope.row.companyName.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="下单" align="center">
          <template slot-scope="scope">
            {{ scope.row.approver }}<br />{{
              parseTime(scope.row.approvedTime, "{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column label="总件数" align="center" prop="total" />
        <el-table-column label="通知收货量" align="center" prop="notifiedCount" />
        <el-table-column label="采购员" align="center" prop="userName" />
        <el-table-column label="运费" align="center" prop="freight" />
        <el-table-column label="优惠金额" align="center" prop="discountAmount" />
        <el-table-column label="应付金额" align="center" prop="amountDue" />
        <el-table-column label="入库状态" align="center" prop="inboundStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.inbound_status" :value="scope.row.inboundStatus" />
          </template>
        </el-table-column>
        <el-table-column label="入库总数量" align="center" prop="inboundNumber" />
        <el-table-column label="付款状态" align="center" prop="paymentStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.payment_status" :value="scope.row.paymentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" :disabled="scope.row.allWaitingStockZero == 1"
              @click="handleChoose(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParamOrder.pageNum"
        :limit.sync="queryParamOrder.pageSize" @pagination="getProcuredOrdersList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelStorage">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 新增收货单中添加产品按钮弹窗 -->
    <el-dialog :title="ordersProductTitle" :visible.sync="ordersProductOpen" width="75%" append-to-body
      :close-on-click-modal="false">
      <el-form :model="queryParamProduct" ref="queryDetails" size="small" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="商品编号 " prop="productProNo">
          <el-input v-model="queryParamProduct.productProNo" placeholder="请输入商品编号 " clearable
            @keyup.enter.native="handleDetails" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParamProduct.productName" placeholder="请输入产品名称" clearable
            @keyup.enter.native="handleDetails" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetails">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetDetails">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="OrdersProductListDetails" height="600px" ref="myTable"
        :span-method="skuSpanMethodDetails" @select="handleSelect" @select-all="handleSelectAll"
        @selection-change="handleSelectionChangeOrdersId" row-key="id">
        <!-- 复选框列 -->
        <el-table-column type="selection" align="center" :selectable="isRowSelectable" />
        <!-- 产品编号 -->
        <el-table-column label="产品编号" align="center" prop="productProNo">
          <template #default="scope">
            <!-- 只有分组首行才显示内容 -->
            <span v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              {{ scope.row.productProNo }}
            </span>
          </template>
        </el-table-column>
        <!-- 图片 -->
        <el-table-column prop="imgName" label="图片" align="center" min-width="100">
          <template #default="scope">
            <div v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex" class="image-container">
              <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                :height="50" class="image-item" />
            </div>
          </template>
        </el-table-column>
        <!-- 品名/SKU -->
        <el-table-column align="center" prop="sku" label="品名/SKU">
          <template #default="scope">
            <div v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              <!-- 只在首行显示品名 + SKU -->
              {{ scope.row.productName }} <br />
              {{ scope.row.sku }}
            </div>
          </template>
        </el-table-column>
        <!-- GTIN 不进行合并 -->
        <el-table-column label="GTIN" align="center" prop="gtin" />

        <!-- 采购量（需要对同 SKU 的多行进行汇总） -->
        <el-table-column label="采购量" align="center">
          <template #default="scope">
            <!-- 只在分组首行显示累加和 -->
            <span v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              {{ skuGroupsDetails[scope.row.sku].sumTransferableNumber }}
            </span>
          </template>
        </el-table-column>
        <!-- 待到货量（汇总） -->
        <el-table-column label="待到货量" align="center">
          <template #default="scope">
            <span v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              {{ skuGroupsDetails[scope.row.sku].sumWaitingStock }}
            </span>
          </template>
        </el-table-column>
        <!-- 已通知量（汇总） -->
        <el-table-column label="已通知" align="center">
          <template #default="scope">
            <span v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              {{ skuGroupsDetails[scope.row.sku].sumNotifiedCount }}
            </span>
          </template>
        </el-table-column>
        <!-- 未通知量（汇总） -->
        <el-table-column label="未通知" align="center">
          <template #default="scope">
            <span v-if="scope.$index === skuGroupsDetails[scope.row.sku].firstIndex">
              {{ skuGroupsDetails[scope.row.sku].sumUnnotifiedQuantity < 0 ? 0 :
                skuGroupsDetails[scope.row.sku].sumUnnotifiedQuantity }} </span>
          </template>
        </el-table-column>

        <!-- 操作列，也合并成一行 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="
              scope.$index === skuGroupsDetails[scope.row.sku].firstIndex &&
              (skuGroupsDetails[scope.row.sku].sumWaitingStock - skuGroupsDetails[scope.row.sku].sumNotifiedCount) > 0
            " size="mini" type="text" icon="el-icon-check" @click="bulkSelection(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParamProduct.pageNum"
        :limit.sync="queryParamProduct.pageSize" @pagination="getListOrdersId" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetails">取 消</el-button>
        <el-button type="primary" @click="submitDetails">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 确认收货的收货单对话框 -->
    <el-dialog :title="receiveTitle" :visible.sync="receiveOpen" width="1600px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="form" :model="formReceive" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收货仓库" prop="warehouseId">
              <treeselect v-model="formReceive.warehouseId" :options="warehouseOptions" :show-count="true"
                placeholder="仓库" :disabled="true" />
            </el-form-item>
            <el-form-item label="预约到货时间" prop="receiptTime">
              <el-date-picker clearable v-model="formReceive.receiptTime" type="date" value-format="yyyy-MM-dd"
                style="width: 275px" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- <el-form-item label="来源单据号" prop="ordersId">
              <treeselect v-model="formReceive.ordersId" :options="OrderNumberOptions" :show-count="true"
                :disabled="true" placeholder="订单编号" />
              <el-input v-model="formReceive.ordersId" :disabled="true"/>
            </el-form-item> -->
            <el-form-item label="来源单据号" prop="ordersNumber">
              <el-input v-model="formReceive.ordersNumber" placeholder="订单编号" disabled />
            </el-form-item>
            <el-form-item label="运费" prop="receiptNumber">
              <el-input v-model="formReceive.freight" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="name">
              <el-input v-model="formReceive.name" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购人员" prop="userName">
              <el-input v-model="formReceive.userName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="receiptRemark">
          <el-input v-model="formReceive.receiptRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">收货单信息</el-divider>
        <el-table :data="DTOReceiptProductsList" :row-class-name="rowReceiptProductsIndex"
          @selection-change="handleReceiptProductsSelectionChange" ref="DTOReceiptProducts" height="329px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="图片" prop="imgName" align="center" min-width="100">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="产品编号" align="center" prop="productProNo" />
          <el-table-column label="品名/SKU" align="center" prop="sku">
            <template slot-scope="scope">
              {{ scope.row.productName }}<br />{{ scope.row.sku }}
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" min-width="120" prop="gtins">
            <template slot-scope="scope">
              <div v-if="scope.row.gtins && scope.row.gtins.length">
                <div v-for="(gtin, index) in scope.row.gtins" :key="index">{{ gtin }}</div>
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="通知收货量" align="center" prop="notificationQuantity"></el-table-column>
          <el-table-column label="收货量" prop="receiptQuantity">
            <template slot-scope="scope">
              <el-input v-model="scope.row.receiptQuantity" placeholder="请输入收货量" :style="{ width: '100px' }" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="detailsRemark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.detailsRemark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormReceive">确认收货</el-button>
        <el-button @click="cancelUpdate(2)">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 质检弹窗 -->
    <el-dialog title="质检" :visible.sync="qualityDialogVisible" width="70%" append-to-body :close-on-click-modal="false">
      <!-- 限制内容高度，添加滚动条 -->
      <div style="height: 650px; overflow-y: auto;">
        <el-table :data="qualityInspectionData" border height="100%">
          <el-table-column label="收货单号" prop="receiptNumber" align="center" />
          <el-table-column label="图片" prop="imgName" align="center" min-width="100">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="品名" align="center" prop="productName">
            <template slot-scope="scope">
              {{ scope.row.productName }}<br />
            </template>
          </el-table-column>
          <el-table-column label="SKU" align="center" prop="sku">
            <template slot-scope="scope">
              <span>{{ scope.row.sku ? scope.row.sku : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" min-width="120" prop="gtins">
            <template slot-scope="scope">
              <div v-if="scope.row.gtins && scope.row.gtins.length">
                <div v-for="(gtin, index) in scope.row.gtins" :key="index">{{ gtin }}</div>
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="未质检" prop="notInspected" align="center" />
          <el-table-column align="center">
            <template slot="header">
              <span>本次质检量</span>
              <el-link @click="setAllInspectionQuantities" style="color: blue; margin-left: 10px;">全部质检</el-link>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.notInspected === 0">
                已全部质检
              </div>
              <el-input v-else v-model.number="scope.row.currentInspectionQuantity" placeholder="请输入质检量"
                style="width: 100px" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qualityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQualityInspection" :loading="loading">质检</el-button>
      </div>
    </el-dialog>
    <!-- 免检弹窗 -->
    <el-dialog title="免检" :visible.sync="exemptDialogVisible" width="1200px" append-to-body
      :close-on-click-modal="false">
      <!-- 限制内容高度，添加滚动条 -->
      <div style="height: 650px; overflow-y: auto;">
        <el-table :data="exemptInspectionData" border height="100%">
          <el-table-column label="收货单号" prop="receiptNumber" align="center" />
          <el-table-column label="图片" prop="imgName" align="center" min-width="100">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="品名" align="center" prop="productName">
            <template slot-scope="scope">
              {{ scope.row.productName }}<br />
            </template>
          </el-table-column>
          <el-table-column label="SKU" align="center" prop="sku">
            <template slot-scope="scope">
              <span>{{ scope.row.sku ? scope.row.sku : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" min-width="120" prop="gtins">
            <template slot-scope="scope">
              <div v-if="scope.row.gtins && scope.row.gtins.length">
                <div v-for="(gtin, index) in scope.row.gtins" :key="index">{{ gtin }}</div>
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="未质检" prop="notInspected" align="center" />
          <el-table-column align="center">
            <template slot="header">
              <span>本次免检量</span>
              <el-link @click="setAllExemptQuantities" style="color: blue; margin-left: 10px;">全部免检</el-link>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.notInspected === 0">
                已全部质检
              </div>
              <el-input v-else v-model.number="scope.row.currentInspectionQuantity" placeholder="请输入免检量"
                style="width: 100px" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exemptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExemptInspection" :loading="loading">免检</el-button>
      </div>
    </el-dialog>


    <!-- 批量收货弹窗 -->
    <el-dialog :title="'批量收货'" :visible.sync="batchOpen" width="85%" append-to-body :close-on-click-modal="false">
      <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" height="600px" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收货仓库" prop="warehouseId">
              <treeselect v-model="batchForm.warehouseId" :options="warehouseOptions" placeholder="请选择仓库"
                @input="onBatchWarehouseChange" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="来源单据号" prop="ordersIds">
              <el-button type="primary" @click="openSelectOrdersDialog" :disabled="!batchForm.warehouseId">
                选择来源单据号
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 显示已选择的来源单据号 -->
        <div v-if="batchForm.selectedOrders.length > 0" style="margin-top: 10px;">
          <!-- 主表格 -->
          <el-table :data="batchForm.selectedOrders" style="width: 100%;">
            <!-- 采购单号 -->
            <el-table-column prop="ordersNumber" label="采购单号" align="center" width="150"></el-table-column>
            <!-- 采购计划号 -->
            <el-table-column prop="planNumber" label="采购计划号" align="center" width="150"></el-table-column>
            <!-- 快递单号 -->
            <el-table-column label="快递单号" align="center" prop="expressNumber">
              <template #default="scope">
                {{ scope.row.expressNumber || '-' }}
              </template>
            </el-table-column>
            <!-- 寄往仓库 -->
            <el-table-column label="寄往仓库" align="center" prop="companyName">
              <template slot-scope="scope">
                <span v-if="scope.row.companyName">
                  {{ scope.row.companyName.slice(0, 10) }}
                  <span v-if="scope.row.companyName.length > 10">...</span>
                </span>
              </template>
            </el-table-column>
            <!-- 下单 -->
            <el-table-column label="下单" align="center">
              <template slot-scope="scope">
                {{ scope.row.approver }}<br />{{
                  parseTime(scope.row.approvedTime, "{y}-{m}-{d}")
                }}
              </template>
            </el-table-column>
            <!-- 总件数 -->
            <el-table-column prop="total" label="总件数" align="center" width="100"></el-table-column>
            <!-- 采购员 -->
            <el-table-column prop="userName" label="采购员" align="center" width="100"></el-table-column>
            <!-- 运费 -->
            <el-table-column prop="freight" label="运费" align="center" width="100"></el-table-column>
            <!-- 优惠金额 -->
            <el-table-column label="优惠金额" align="center" prop="discountAmount">
              <template #default="scope">
                {{ scope.row.discountAmount || '-' }}
              </template>
            </el-table-column>
            <!-- 应付金额 -->
            <el-table-column prop="amountDue" label="应付金额" align="center" width="100"></el-table-column>

            <!-- 可展开列 -->
            <el-table-column type="expand">
              <template #default="props">
                <!-- 展开显示子表格 -->
                <el-table :data="props.row.DTOReceiptProductsList" style="width: 100%;">
                  <el-table-column label="产品编号 " align="center" prop="productProNo" />
                  <el-table-column label="图片" prop="imgName" align="center" min-width="100">
                    <template slot-scope="scope">
                      <div class="image-container">
                        <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                          :height="50" class="image-item" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="品名/SKU" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.productName }}<br />{{ scope.row.sku }}
                    </template>
                  </el-table-column>
                  <el-table-column label="GTIN " align="center" prop="gtin" />
                  <el-table-column label="产品单价 " align="center" prop="productPrice" />
                  <el-table-column label="采购仓库" align="center" prop="warehouseName" />
                  <el-table-column label="采购量" align="center" prop="transferableNumber" />
                  <el-table-column label="待到货量" align="center" prop="waitingStock" />
                  <el-table-column label="已通知" align="center" prop="notifiedCount" />
                  <el-table-column label="未通知" align="center">
                    <template slot-scope="scope">
                      <span>{{ scope.row.unnotifiedQuantity < 0 ? 0 : scope.row.unnotifiedQuantity }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button type="text" size="small" @click="removeSelectedOrder(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitBatchForm" :loading=loading>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 选择来源单据号弹窗 -->
    <el-dialog :title="'选择来源单据号'" :visible.sync="selectOrdersDialogVisible" width="85%" append-to-body
      :close-on-click-modal="false">
      <el-form :model="batchForm" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="采购单号" prop="ordersNumber">
          <el-input v-model="batchForm.ordersNumber" placeholder="请输入采购单号" clearable
            @keyup.enter.native="listUnreceivedOrders" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="listUnreceivedOrders">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetBatchOrdersForm">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="ProcuredOrdersList" height="554px" empty-text="暂无可批量收货的采购订单"
        @selection-change="handleSelectionOrdersChange" ref="tableRef" row-key="ordersId" reserve-selection>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购单号" align="center" prop="ordersNumber" />
        <el-table-column label="采购计划号" align="center" prop="planNumber" />
        <el-table-column label="寄往仓库" align="center" prop="companyName">
          <template slot-scope="scope">
            <span v-if="scope.row.companyName">
              {{ scope.row.companyName.slice(0, 10) }}
              <span v-if="scope.row.companyName.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="下单" align="center">
          <template slot-scope="scope">
            {{ scope.row.approver }}<br />{{
              parseTime(scope.row.approvedTime, "{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column label="总件数" align="center" prop="total" />
        <el-table-column label="通知收货量" align="center" prop="notifiedCount" />
        <el-table-column label="采购员" align="center" prop="userName" />
        <el-table-column label="运费" align="center" prop="freight" />
        <el-table-column label="应付金额" align="center" prop="amountDue" />
        <el-table-column label="入库状态" align="center" prop="inboundStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.inbound_status" :value="scope.row.inboundStatus" />
          </template>
        </el-table-column>
        <el-table-column label="入库总数量" align="center" prop="inboundNumber" />
        <el-table-column label="付款状态" align="center" prop="paymentStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.payment_status" :value="scope.row.paymentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- 切换选择与已选择状态 -->
            <el-button v-show="!selectedOrdersList.includes(scope.row.ordersId)"
              @click="toggleOrderSelection(scope.row)" size="small">选择</el-button>
            <el-button v-show="selectedOrdersList.includes(scope.row.ordersId)" @click="toggleOrderSelection(scope.row)"
              type="primary" size="small">已选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="batchForm.pageNum" :limit.sync="batchForm.pageSize"
        :default-limit="10" @pagination="loadAvailableOrders" />


      <div slot="footer" class="dialog-footer">
        <el-button @click="selectOrdersDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectOrders">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listReceipt,
  getReceipt,
  getUpdateReceipt,
  delReceipt,
  addReceipt,
  updateReceipt,
  updateReceiptConfirm,
  getProcuredOrdersTree,
  getSelectOrdersNumber,
  getReceiptQuantity,
  someApiCall,
  batchAddInspection,
  batchAddReceipt
} from "@/api/depot/receipt";
import {
  getSelectByOrderIdList,
  getSelectByIds,
  getUpdateDetailsStatus,
  getSelectListProductId,
  getUpdateProductIdDetailsStatus,
  getUpdateTestDetailsStatus,
} from "@/api/depot/voOrdersProduct";
import {
  getSelectPreWarehouseTreeList,
  getSelectVendorTreeList,
} from "@/api/procured/plan";
import {
  addInspection
} from "@/api/depot/inspection";
import {
  listReceiptProcuredOrders,
  listUnreceivedOrders,
  getOrdersDetails
} from "@/api/orders/ProcuredOrders";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { ElIcon } from 'element-ui';
export default {
  name: "Receipt",
  dicts: [
    "tb_receipt",
    "tb_receipt_proudct_quality_status",
    "inbound_status",
    "payment_status",
    'tb_quality_inspection_status'
  ],
  components: { Treeselect, ElIcon },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idss: [],
      // 子表选中数据
      checkedReceiptProducts: [],
      isBulkSelectingReceipt: false,   // 屏蔽中间触发的 selection-change
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multipleId: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收货单表格数据
      receiptList: [],
      // 收货单表格数据
      DTOReceiptProductsList: [],
      // 弹出层标题
      title: "",
      orderIdTitle: "",
      ordersProductTitle: "",
      updateTitle: "",
      receiveTitle: "",
      // 是否显示弹出层
      open: false,
      orderIdOpen: false,
      ordersProductOpen: false,
      updateOpen: false,
      receiveOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptNumber: null,
        receiptTime: null,
        receiptStatus: null,
      },
      // 表单参数
      form: { name: null, userName: null },
      formUpdate: {},
      formReceive: {},
      // 表单校验
      rules: {},
      select: "1",
      // 仓库列表
      warehouseOptions: [],
      //采购订单列表
      procuredOrdersOptions: [],
      OrderNumberOptions: [],
      // 供应商
      vendorOptions: [],
      hasWarehouseContent: true,
      // 查询采购单号
      queryParamOrder: {
        pageNum: 1,
        pageSize: 10,
        ordersNumber: null,
        planId: null,
        inboundStatus: 1,
        warehouseId: null,
        receiptNoOrderStatus: 9
      },
      // 采购订单表格数据
      ProcuredOrdersList: [],
      // 产品明细查询参数
      queryParamProduct: {
        pageNum: 1,
        pageSize: 10,
        productProNo: null,
        productName: null,
        ordersId: null,
        receiptProductIds: [],
        receiptId: null,
        ordersProductIds: [],
      },
      // 产品明细表格数据
      OrdersProductListDetails: [],
      //确认入库用来做判断的
      procuredFlay: true,
      //用来标识是修改弹窗中添加产品还是添加弹窗中添加产品
      isFlag: false,
      qualityDialogVisible: false, // 控制质检弹窗的显示
      qualityInspectionData: [], // 质检数据
      receiptStatus: [],//用于存储收货单状态
      exemptDialogVisible: false, // 控制免检弹窗的显示
      exemptInspectionData: [],   // 存储免检数据
      batchQualityEnabled: false, // 控制“批量质检”按钮的启用状态
      list: [], //用于存储批量质检时提交的数据

      batchOpen: false, // 控制批量收货弹窗的显示
      batchForm: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        inboundStatus: 1,
        unreceivedOrdersFlag: 1, // 用于查询未被收货过的采购订单
        ordersNumber: '', // 采购单号
        ordersIds: [], // 选中的来源单据号ID列表
        selectedOrders: [], // 选中的来源单据详细信息
      },
      batchRules: {
        warehouseId: [{ required: true, message: '请选择收货仓库', trigger: 'change' }],
        ordersIds: [{ required: true, message: '请选择来源单据号', trigger: 'change' }],
      },
      selectOrdersDialogVisible: false, // 控制选择来源单据号弹窗的显示
      availableOrders: [], // 可供选择的未收货的来源单据号列表
      selectedOrdersList: [], // 临时存储在弹窗中选中的来源单据号

      exemptOrdersId: null,// 用于免检时提交数据临时使用
      isUpdating: false,  // 是否是修改模式
      isBulkSelecting: false,
    };
  },
  created() {
    this.getList();
    this.getPreWarehouse();
    this.getVendor();
    this.getProcuredOrders();
  },
  computed: {
    // ★★ 新增：根据 SKU 对表格数据进行分组，供合并方法使用
    // 按 SKU 分组，并统计首行索引、行列表和各字段汇总
    skuGroupInfo() {
      const map = {};
      this.DTOReceiptProductsList.forEach((item, index) => {
        const sku = item.sku;
        if (!map[sku]) {
          map[sku] = {
            firstIndex: index,
            count: 1,
            rows: [item],
            sumTransferableNumber: Number(item.transferableNumber) || 0,
            sumWaitingStock: Number(item.waitingStock) || 0,
            sumNotifiedCount: Number(item.notifiedCount) || 0,
            sumUnnotifiedQuantity: Number(item.unnotifiedQuantity) || 0,
            sumNotificationQuantity: Number(item.notificationQuantity) || 0,
          };
        } else {
          const g = map[sku];
          g.count++;
          g.rows.push(item);
          g.sumTransferableNumber += Number(item.transferableNumber) || 0;
          g.sumWaitingStock += Number(item.waitingStock) || 0;
          g.sumNotifiedCount += Number(item.notifiedCount) || 0;
          g.sumUnnotifiedQuantity += Number(item.unnotifiedQuantity) || 0;
          g.sumNotificationQuantity += Number(item.notificationQuantity) || 0;
        }
      });
      // console.log(JSON.stringify(map, null, 2));

      return map;
    },
    // 修改收货单弹窗所需计算属性
    skuGroupUpdateInfo() {
      const map = {};
      this.DTOReceiptProductsList.forEach((item, index) => {
        const sku = item.sku;
        if (!map[sku]) {
          map[sku] = {
            firstIndex: index,
            count: 1,
            rows: [item],
            sumTransferableNumber: Number(item.transferableNumber) || 0,
            sumWaitingStock: Number(item.waitingStock) || 0,
            sumNotifiedCount: Number(item.notifiedCount) || 0,
            sumUnnotifiedQuantity: Number(item.unnotifiedQuantity) || 0,
            sumNotificationQuantity: Number(item.notificationQuantity) || 0,
          };
        } else {
          const g = map[sku];
          g.count++;
          g.rows.push(item);
          g.sumTransferableNumber += Number(item.transferableNumber) || 0;
          g.sumWaitingStock += Number(item.waitingStock) || 0;
          g.sumNotifiedCount += 0;
          g.sumUnnotifiedQuantity += Number(item.unnotifiedQuantity) || 0;
          g.sumNotificationQuantity += Number(item.notificationQuantity) || 0;
        }
      });
      console.log('修改之后', JSON.stringify(map, null, 2));

      return map;
    },
    /**
     * 用于给 OrdersProductListDetails 做分组，记录分组首行行号、行数，以及需要合并汇总的字段。
     */
    skuGroupsDetails() {
      const map = {};
      this.OrdersProductListDetails.forEach((item, index) => {
        const sku = item.sku;
        if (!map[sku]) {
          map[sku] = {
            firstIndex: index,
            count: 1,
            rows: [item],                     // ← 新增
            sumTransferableNumber: Number(item.transferableNumber) || 0,
            sumWaitingStock: Number(item.waitingStock) || 0,
            sumNotifiedCount: Number(item.notifiedCount) || 0,
            sumUnnotifiedQuantity: Number(item.unnotifiedQuantity) || 0,
          };
        } else {
          map[sku].count++;
          map[sku].rows.push(item);          // ← 新增
          map[sku].sumTransferableNumber += Number(item.transferableNumber) || 0;
          map[sku].sumWaitingStock += Number(item.waitingStock) || 0;
          map[sku].sumNotifiedCount += Number(item.notifiedCount) || 0;
          map[sku].sumUnnotifiedQuantity += Number(item.unnotifiedQuantity) || 0;
        }
      });
      return map;
    }

  },
  methods: {
    /**
     * 自定义复选框的可选逻辑：只允许“SKU 分组首行”可选，避免出现多行复选框。
     * 且要求 waitingStock - notifiedCount > 0 才能选。
     */
    isRowSelectable(row, index) {
      const group = this.skuGroupsDetails[row.sku];
      if (!group) return false;

      const isFirst = index === group.firstIndex;
      const unnotified = group.sumWaitingStock - group.sumNotifiedCount;
      const canSelect = unnotified > 0;

      return isFirst && canSelect;
    },
    /** 查询收货单列表 */
    getList() {
      this.loading = true;
      const [startTime, endTime] = this.queryParams.receiptTime || [];
      const params = {
        ...this.queryParams,
        startTime,
        endTime,
      };

      // 删除不必要的参数
      delete params.receiptTime;
      listReceipt(params).then((response) => {
        this.receiptList = response.rows;
        this.total = response.total;

        // 添加排序逻辑，将 receiptStatus 为 '0' 的数据排在前面
        this.receiptList.sort((a, b) => {
          if (a.receiptStatus === '0' && b.receiptStatus !== '0') {
            return -1;
          } else if (a.receiptStatus !== '0' && b.receiptStatus === '0') {
            return 1;
          } else {
            return 0;
          }
        });

        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      if (this.DTOReceiptProductsList.length != 0) {
        //getUpdateDetailsStatus(this.DTOReceiptProductsList);
      }
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        receiptId: null,
        receiptNumber: null,
        ordersId: null,
        noticeReceiptQuantity: null,
        receiptQuantity: null,
        consignee: null,
        receiptTime: null,
        receiptStatus: null,
        receiptRemark: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
        warehouseId: null,
        name: null,
        userName: null,
      };
      this.DTOReceiptProductsList = [];
      this.formUpdate = {
        receiptId: null,
        receiptNumber: null,
        ordersId: null,
        noticeReceiptQuantity: null,
        receiptQuantity: null,
        consignee: null,
        receiptTime: null,
        receiptStatus: null,
        receiptRemark: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
        warehouseId: null,
        name: null,
        userName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      //将选择的搜索类型添加到条件中
      this.queryParams.select = this.select
      this.getList();
    },
    handleQueryProduct() {
      this.getProcuredOrdersList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetQueryProduct() {
      this.queryParamOrder.ordersNumber = null;
      this.handleQueryProduct();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.receiptStatus = selection.map((item) => item.receiptStatus)
      this.ids = selection.map((item) => item.receiptId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      // 检查所有选中的收货单状态是否为已收货，且所有产品的质检状态是否为未质检
      this.batchQualityEnabled = selection.length > 0 && selection.every((item) => {
        return item.receiptStatus == '1' && Array.isArray(item.DTOReceiptProductsList) && item.DTOReceiptProductsList.every(product => product.qualityStatus == '4');
      });
      this.list = selection;
    },


    // 批量质检方法
    batchQualityInspection() {
      if (!this.batchQualityEnabled) {
        // 按钮已禁用，无需处理
        return;
      }
      this.$confirm('是否将勾选的收货单进行批量质检?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了确定，准备提交数据
        batchAddInspection(this.list).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("操作成功！");
            this.updateOpen = false;
            this.getList();
          }
        });
      }).catch(() => {
        // 用户取消了操作，无需处理
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isUpdating = false;
      this.reset();
      this.form.receiptTime = new Date(); // 设置到货时间为当前日期
      this.open = true;
      this.title = "添加收货单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isUpdating = true;

      let status = this.receiptStatus[0];
      if (status == 1) {
        this.$message.warning('收货单已收货完成，不能进行修改操作！');
        return; // 阻止进一步执行
      }
      this.reset();
      this.form.receiptTime = new Date(); // 设置到货时间为当前日期
      const receiptId = row.receiptId || this.ids;

      getUpdateReceipt(receiptId).then((response) => {
        this.formUpdate = response.data;
        const data = response.data.DTOReceiptProductsList.sort((a, b) => {
          return a.sku.localeCompare(b.sku);
        });
        this.DTOReceiptProductsList = data;
        // 这段代码是为了将一个SKU对应多个GTIN的情况是，将所有分组内的SKU汇总到一个合计收货量用于展示
        const map = this.skuGroupUpdateInfo;
        // 遍历 map 中每个 SKU 分组
        for (const sku in map) {
          const group = map[sku];
          group.rows.forEach((item, index) => {
            if (index === 0) {
              item.notificationQuantity = group.sumNotificationQuantity;
            } else {
              item.notificationQuantity = 0;
            }
          });
        }
        this.updateOpen = true;
        this.updateTitle = "修改收货单";
      });
    },

    /** 修改取消按钮 */
    cancelUpdate(index) {
      if (index == 1) {
        this.updateOpen = false;
      }
      if (index == 2) {
        this.receiveOpen = false;
      }

      /*
      for (let i = 0; i < this.DTOReceiptProductsList.length; i++) {
        if (this.DTOReceiptProductsList[i].testNotificationQuantity == null) {
          getUpdateTestDetailsStatus(
            false,
            this.DTOReceiptProductsList[i].ordersId,
            this.DTOReceiptProductsList[i].productId
          );
        } else {
          if (
            this.DTOReceiptProductsList[i].testNotificationQuantity ==
            this.DTOReceiptProductsList[i].unnotifiedQuantity
          ) {
            getUpdateTestDetailsStatus(
              true,
              this.DTOReceiptProductsList[i].ordersId,
              this.DTOReceiptProductsList[i].productId
            );
          } else {
            getUpdateTestDetailsStatus(
              false,
              this.DTOReceiptProductsList[i].ordersId,
              this.DTOReceiptProductsList[i].productId
            );
          }
        }
      }
      if(index == 1){
         this.reset();
      }
      if(index == 2){
        this.resetReceive();
      }
      */

    },
    /** 提交修改按钮 */
    submitFormUpdate() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let skuMap = {}; // 用于记录每个sku是否已经满足条件
          let invalidProducts = [];
          this.formUpdate.DTOReceiptProductsList = this.DTOReceiptProductsList;
          for (let i = 0; i < this.formUpdate.DTOReceiptProductsList.length; i++) {
            let product = this.formUpdate.DTOReceiptProductsList[i];
            let sku = product.sku;

            // 如果该sku的通知收货量大于0，跳过这个sku的所有分组
            if (product.notificationQuantity > 0) {
              // this.procuredFlay = true;
              skuMap[sku] = true; // 标记该sku已经有效
            }

            // 如果当前sku没有标记为有效且通知收货量 <= 0，认为是无效产品
            if (product.notificationQuantity <= 0 && !skuMap[sku]) {
              invalidProducts.push(product); // 将不合法的产品添加到数组中
            }
          }

          // 如果存在不合法的产品，显示警告信息
          if (invalidProducts.length > 0) {
            let proNoList = invalidProducts
              .map((product) => product.sku + ':' + product.gtin)
              .join("----"); // 获取不合法的产品编号列表

            this.$modal.msgWarning(
              "产品" + proNoList + "的通知收货量不能为0或负数！"
            );
            // this.procuredFlay = false;
            return;
          }
          this.DTOReceiptProductsList.forEach(item => {
            item.imgName = null;
          }); // 不需要图片插入
          this.formUpdate.DTOReceiptProductsList = this.DTOReceiptProductsList
          console.log(JSON.stringify(this.formUpdate, null, 2));
          updateReceipt(this.formUpdate).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.updateOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let skuMap = {}; // 用于记录每个sku是否已经满足条件
          let invalidProducts = [];
          this.form.DTOReceiptProductsList = this.DTOReceiptProductsList;
          for (let i = 0; i < this.form.DTOReceiptProductsList.length; i++) {
            let product = this.form.DTOReceiptProductsList[i];
            let sku = product.sku;

            // 如果该sku的通知收货量大于0，跳过这个sku的所有分组
            if (product.notificationQuantity > 0) {
              this.procuredFlay = true;
              skuMap[sku] = true; // 标记该sku已经有效
            }

            // 如果当前sku没有标记为有效且通知收货量 <= 0，认为是无效产品
            if (product.notificationQuantity <= 0 && !skuMap[sku]) {
              invalidProducts.push(product); // 将不合法的产品添加到数组中
            }
          }

          // 如果存在不合法的产品，显示警告信息
          if (invalidProducts.length > 0) {
            let proNoList = invalidProducts
              .map((product) => product.sku + ':' + product.gtin)
              .join("----"); // 获取不合法的产品编号列表

            this.$modal.msgWarning(
              "产品" + proNoList + "的通知收货量不能为0或负数！"
            );
            this.procuredFlay = false;
            return;
          }

          // 如果所有产品通知量都有效，提交表单
          if (this.procuredFlay == true) {
            if (this.form.DTOReceiptProductsList.length == 0) {
              this.$modal.msgWarning("您还未选择要收货的产品信息！");
            } else {
              this.DTOReceiptProductsList.forEach(item => {
                item.imgName = null;
              }); // 不需要图片插入
              this.form.DTOReceiptProductsList = this.DTOReceiptProductsList;
              console.log(JSON.stringify(this.form, null, 2));
              addReceipt(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      // 检查是否所有选中的收货单状态都为未收货完成
      const allUnlocked = this.receiptStatus.every((status) => status == 0);
      if (!allUnlocked) {
        this.$message.warning('存在已收货完成的收货单，不能进行删除！');
        return;
      }
      if (row.receiptStatus == 1) {
        this.$message.warning('收货单已收货完成，不能进行删除操作！');
        return;
      }
      // 构建选中收货单的编号列表（用于展示在提示框中）
      const receiptNumbers = row.receiptNumber || this.list
        .map((item) => item.receiptNumber)
        .join(', ');
      const receiptIds = row.receiptId || this.ids;
      // 提示确认框
      this.$modal
        .confirm('是否确认删除以下收货单编号："' + receiptNumbers + '"？')
        .then(() => {
          // 调用删除接口，删除选中的收货单
          return delReceipt(receiptIds);
        })
        .then(() => {
          // 删除成功后刷新列表
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {
          // 用户取消操作
        });
    },
    /** 收货单序号 */
    rowReceiptProductsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 收货单添加按钮操作 */
    handleAddReceiptProducts() {
      if (this.form.warehouseId == null) {
        this.$modal.msgError("您还未选择仓库");
      } else {
        if (this.form.ordersId == null) {
          this.$modal.msgError("您还未选择来源单据号");
        } else {
          this.isFlag = false; //代表是新增窗口中添加产品
          this.ordersProductTitle = "添加产品";
          this.ordersProductOpen = true;
          this.queryParamProduct.receiptId = null;
          this.queryParamProduct.ordersId = this.form.ordersId;
          this.queryParamProduct.receiptProductIds = [];
          this.queryParamProduct.ordersProductIds = [];
          for (let i = 0; i < this.DTOReceiptProductsList.length; i++) {
            this.queryParamProduct.ordersProductIds.push(this.DTOReceiptProductsList[i].id);
          }
          console.log(JSON.stringify(this.DTOReceiptProductsList, null, 2));

          this.getListOrdersId();
        }
      }
    },
    /** 收货单修改按钮操作 */
    handleUpdateReceiptProducts() {
      this.isFlag = true; //代表是修改弹窗中添加产品
      this.ordersProductTitle = "添加产品";
      this.ordersProductOpen = true;
      this.queryParamProduct.ordersId = this.formUpdate.ordersId;
      this.queryParamProduct.receiptId = null;
      // this.queryParamProduct.receiptId = this.formUpdate.receiptId;
      this.queryParamProduct.receiptProductIds = [];
      this.queryParamProduct.ordersProductIds = [];
      for (let i = 0; i < this.DTOReceiptProductsList.length; i++) {
        this.queryParamProduct.ordersProductIds.push(this.DTOReceiptProductsList[i].ordersProductId);
      }
      this.getListOrdersId();
      // getSelectListProductId(this.formUpdate.ordersId).then((response) => {
      // for (let i = 0; i < this.DTOReceiptProductsList.length; i++) {
      //   this.queryParamProduct.receiptProductIds.push(this.DTOReceiptProductsList[i].receiptProudctId);

      //   if (this.DTOReceiptProductsList[i].receiptProudctId == null || this.DTOReceiptProductsList[i].receiptProudctId == '') {
      //     this.queryParamProduct.ordersProductIds.push(this.DTOReceiptProductsList[i].id);
      //   }
      //   // for (let z = 0; z < response.data.length; z++) {
      //   /*
      //   if (
      //     this.DTOReceiptProductsList[i].productId ==
      //     response.data[z].productId
      //   ) {
      //     getUpdateProductIdDetailsStatus(response.data[z].id);
      //     this.getListOrdersId();
      //   }
      //   */
      //   // }
      // }

      // });
    },
    /** 收货单删除按钮操作 */
    // handleDeleteReceiptProducts() {
    //   if (this.checkedReceiptProducts.length == 0) {
    //     this.$modal.msgError("请先选择要删除的收货单数据");
    //   } else {
    //     //getUpdateDetailsStatus(this.checkedReceiptProducts);
    //     const DTOReceiptProductsList = this.DTOReceiptProductsList;
    //     const checkedReceiptProducts = this.checkedReceiptProducts;
    //     this.DTOReceiptProductsList = DTOReceiptProductsList.filter(function (item) {
    //       return checkedReceiptProducts.indexOf(item) == -1;
    //     });
    //   }
    // },
    handleDeleteReceiptProducts() {
      if (!this.checkedReceiptProducts.length) {
        this.$modal.msgError("请先选择要删除的收货单数据");
        return;
      }
      // 1. 收集要删除的 sku
      const skusToDelete = new Set(
        this.checkedReceiptProducts.map(item => item.sku)
      );
      // 2. 过滤掉这些 sku 的所有行
      this.DTOReceiptProductsList = this.DTOReceiptProductsList.filter(
        item => !skusToDelete.has(item.sku)
      );
      // 3. 清空 selection
      this.$nextTick(() => {
        this.$refs.DTOReceiptProducts.clearSelection();
        this.checkedReceiptProducts = [];
      });
    },
    /** 复选框选中数据 */
    // handleReceiptProductsSelectionChange(selection) {
    //   this.checkedReceiptProducts = selection.map((item) => item);
    // },
    handleReceiptProductsSelectionChange(selection) {
      if (this.isBulkSelectingReceipt) {
        return;
      }
      this.checkedReceiptProducts = selection.slice(); // 保留一份副本
    },

    handleSelectionChangeOrdersId(selection) {
      if (this.isBulkSelecting) {
        return;
      }
      this.idss = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "depot/receipt/export",
        {
          ...this.queryParams,
        },
        `receipt_${new Date().getTime()}.xlsx`
      );
    },

    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },
    /** 查询采购订单 */
    getProcuredOrders() {
      const ordersNumber = 1;
      getProcuredOrdersTree(ordersNumber).then((response) => {
        this.OrderNumberOptions = response.data;
      });
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    updateWarehouseContent() {
      this.DTOReceiptProductsList = [];
      this.procuredOrdersOptions = [];
      this.queryParamOrder.warehouseId = this.form.warehouseId;
      this.hasWarehouseContent = this.form.warehouseId === undefined;
      this.form.ordersId = null;
      // 查询出除了已入库以外的所有订单
      this.form.inboundStatus = 1;
      // 加上这个为了在后端的查询出尚未完全通知收货或发货的采购单
      this.form.ordersNumber = 1;
      getProcuredOrdersTree(this.form).then((response) => {
        let data = response.data;

        // 去重操作，基于 id 属性
        let uniqueData = [];
        let ids = new Set();
        data.forEach(item => {
          if (!ids.has(item.id)) {
            ids.add(item.id);
            uniqueData.push(item);
          }
        });

        // 添加特殊选项
        uniqueData.push({ id: -1, label: "更多来源订单号", disabled: true });
        this.procuredOrdersOptions.unshift(...uniqueData);
      });
    },

    /** 当添加收货单中来源单据号变化时触发 */
    checkOpenDialog(value) {
      if (value !== undefined && value !== null) {
        if (value == -1) {
          this.orderIdOpen = true;
          this.orderIdTitle = "选择采购单";
          this.form.ordersId = null;
          this.getProcuredOrdersList();
        } else {
          this.loading = true;  // 开始加载
          this.DTOReceiptProductsList = [];
          getSelectOrdersNumber(value).then((response) => {
            if (response.data != null) {
              this.form.name = response.data.name;
              this.form.userName = response.data.userName;
              this.form.freight = response.data.freight;
            }
          }).finally(() => {
            this.loading = false;  // 完成加载
          });
        }
      } else {
        this.form.name = null;
        this.form.userName = null;
        this.form.freight = null;
      }
    },

    /** 查询采购订单列表 */
    getProcuredOrdersList() {
      this.loading = true;
      listReceiptProcuredOrders(this.queryParamOrder).then((response) => {
        // 对返回的数据按 allWaitingStockZero 排序，将 allWaitingStockZero 为 0 的数据排在前面
        this.ProcuredOrdersList = response.rows.sort((a, b) => {
          return a.allWaitingStockZero - b.allWaitingStockZero;
        });

        // 设置总数和加载状态
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 选择 */
    handleChoose(row) {
      if (row && row.ordersNumber) {
        // 允许自定义值，如果该值不在 options 中，就添加一个临时的选项
        const exists = this.procuredOrdersOptions.some(
          (option) => option.id === row.ordersId
        );

        if (!exists) {
          this.procuredOrdersOptions.unshift({
            label: row.ordersNumber,
            id: row.ordersId,
            status: null,
            value: null
          });
        }

        this.form.ordersId = row.ordersId;
      }
      this.orderIdOpen = false;
    },


    /** 取消 */
    cancelStorage() {
      this.orderIdOpen = false;
      this.getList();
    },
    /** 产品搜索按钮操作 */
    handleDetails() {
      this.queryParamProduct.pageNum = 1;
      this.getListOrdersId();
    },
    /** 产品重置按钮操作 */
    resetDetails() {
      this.resetForm("queryDetails");
      this.handleDetails();
    },
    /** 通过采购单id查询需要入库的数据 */
    getListOrdersId() {
      getSelectByOrderIdList(this.queryParamProduct).then((response) => {
        this.OrdersProductListDetails = response.rows;
        this.total = response.total
        //说明是在修改收货单弹窗中点击的添加产品按钮，进行处理
        // if(!this.isFlag){
        //    this.OrdersProductListDetails.forEach(product => {
        //       product.
        //     });
        // }
        // this.$nextTick(() => {
        //   this.$refs.myTable.clearSelection();
        //   let count = this.OrdersProductListDetails.length;
        //   for (let i = 0; i < count; i++) {
        //     if (this.OrdersProductListDetails[i].isChecked == '0') {
        //       this.$refs.myTable.toggleRowSelection(this.OrdersProductListDetails[i], true);
        //     }
        //   }
        // })
      });
    },

    /** 产品明细取消 */
    cancelDetails() {
      this.ordersProductOpen = false;
      this.$refs.myTable.clearSelection();
      this.getList();
    },
    /** 产品明细确定 */
    submitDetails(row) {
      let list = this.OrdersProductListDetails;
      this.DTOReceiptProductsList = this.DTOReceiptProductsList || []; // 确保列表已初始化

      for (let i = 0; i < list.length; i++) {
        let productId = list[i].productId;
        let ordersId = list[i].ordersId;
        let gtin = list[i].gtin;
        // 检查当前 DTOReceiptProductsList 中是否已经有该商品
        let exists = this.DTOReceiptProductsList.some(
          (item) => item.productId == productId && item.ordersId == ordersId && item.gtin == gtin
        );

        // 如果不存在才添加
        if (!exists && this.idss.indexOf(list[i].id) >= 0) {
          let obj = {
            id: list[i].id,
            imgName: list[i].imgName,
            productName: list[i].productName,
            sku: list[i].sku,
            transferableNumber: list[i].transferableNumber,
            waitingStock: list[i].waitingStock,
            notifiedCount: list[i].notifiedCount,
            unnotifiedQuantity: list[i].unnotifiedQuantity,
            notificationQuantity: 0, // row.notificationQuantity;
            productId: list[i].productId,
            productProNo: list[i].productProNo,
            ordersId: list[i].ordersId,
            receiptProudctId: list[i].receiptProductId,
            gtin: list[i].gtin
          };
          this.DTOReceiptProductsList.push(obj);
        }
      }
      console.log('DTOReceiptProductsList', JSON.stringify(this.DTOReceiptProductsList, null, 2));
      this.ordersProductOpen = false;
    },
    /** 产品明细选择 */
    bulkSelection(row) {
      // 找到所有与当前行 SKU 相同的行（同一 SKU 分组的产品）
      const groupRows = this.OrdersProductListDetails.filter(
        item => item.sku === row.sku
      );

      // 检查是否已存在该分组的商品
      const exists = groupRows.every(item =>
        this.DTOReceiptProductsList.some(
          listItem => listItem.productId === item.productId && listItem.gtin === item.gtin
        )
      );

      if (!exists) {
        // 如果该 SKU 分组的商品未添加到 DTOReceiptProductsList 中，添加整个 SKU 分组
        groupRows.forEach(item => {
          let obj = {};
          if (!this.isFlag) {
            obj.id = item.id;
          } else {
            obj.ordersProductId = item.id;
          }

          // 复制每个产品的属性到 obj
          obj.imgName = item.imgName;
          obj.productName = item.productName;
          obj.sku = item.sku;
          obj.transferableNumber = item.transferableNumber;
          obj.waitingStock = item.waitingStock;
          obj.notifiedCount = item.notifiedCount;
          obj.unnotifiedQuantity = item.unnotifiedQuantity;
          obj.notificationQuantity = 0; // 初始化为0
          obj.productId = item.productId;
          obj.productProNo = item.productProNo;
          obj.ordersId = item.ordersId;
          obj.receiptProudctId = item.receiptProductId;
          obj.gtin = item.gtin;

          // 将该产品加入 DTOReceiptProductsList
          this.DTOReceiptProductsList.push(obj);
        });

        // 关闭弹窗
        this.ordersProductOpen = false;
      } else {
        // 如果商品已存在，提示用户
        this.$modal.msgWarning(`商品 ${row.sku} 已存在于列表中。`);
      }
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleReceived":
          this.handleReceived(row);
          break;
        case "handleQualityCheck":
          this.handleQualityCheck(row);
          break;
        case "handleExemptCheck":
          this.handleExemptCheck(row);
          break;
        default:
          break;
      }
    },
    // 质检按钮点击事件
    async handleQualityCheck(row) {
      try {
        this.queryParamProduct.receiptId = row.receiptId//存储收货单id，用于在提交质检单的时候使用
        this.exemptOrdersId = row.ordersId
        // 获取收货单详情
        const response = await getReceipt(row.receiptId);
        this.qualityDialogVisible = true;

        // 先过滤掉 notInspected 为 0 的项
        // const filteredProducts = response.data.DTOReceiptProductsList.filter(item => item.notInspected !== 0);

        // 将返回的数据填充到 qualityInspectionData 中
        this.qualityInspectionData = response.data.DTOReceiptProductsList.map(item => ({
          receiptNumber: row.receiptNumber,
          imgName: item.imgName,
          productName: item.productName,
          sku: item.sku,
          notInspected: item.notInspected,
          currentInspectionQuantity: null,
          productId: item.productId,
          receiptProductId: item.receiptProductId,
          receiptId: item.receiptId,
          transferableNumber: item.transferableNumber,
          waitingStock: item.waitingStock,
          notifiedCount: item.notifiedCount,
          unnotifiedQuantity: item.unnotifiedQuantity,
          receiptQuantity: item.receiptQuantity,
          pendingQuantity: item.pendingQuantity,
          qualityInspection: item.qualityInspection,
          checkedQuantity: item.checkedQuantity,
          availableQuantity: item.availableQuantity,
          defectiveQuantity: item.defectiveQuantity,
          qualityStatus: item.qualityStatus,
          deleteStatus: item.deleteStatus,
          createTime: item.createTime,
          detailsRemark: item.detailsRemark,
          productProNo: item.productProNo,
          ordersId: item.ordersId,
          id: item.id,
          testNotificationQuantity: item.testNotificationQuantity,
          ordersProductId: item.ordersProductId,
          warehouseId: response.data.warehouseId,
          gtin: item.gtin,
          gtins: item.gtins
        }));
      } catch (error) {
        // 错误处理
        this.$message.error("获取收货单详情失败，请重试");
        console.error("Error fetching receipt details:", error);
      }
    },
    // 全部质检操作
    setAllInspectionQuantities() {
      this.qualityInspectionData.forEach((row) => {
        row.currentInspectionQuantity = row.notInspected;
      });
    },
    // 提交质检
    async submitQualityInspection() {
      this.loading = true; // 开始加载
      try {
        // 过滤掉未质检量为0，或本次质检量输入为0的数据
        const validInspectionData = this.qualityInspectionData.filter(item => item.currentInspectionQuantity > 0);

        // 如果没有有效的质检数据，提示用户并停止提交
        if (validInspectionData.length === 0) {
          this.$message.warning("没有有效的质检数据，请检查输入。");
          return;
        }
        // 校验本次质检量
        const invalidItems = this.qualityInspectionData.filter(item => {
          const currentInspectionQuantity = Number(item.currentInspectionQuantity);
          return currentInspectionQuantity < 0 || currentInspectionQuantity > item.notInspected;
        });

        // 如果有不符合条件的项，显示错误消息并停止提交
        if (invalidItems.length > 0) {
          const invalidDescriptions = invalidItems.map(item => `品名: ${item.productName}，SKU: ${item.sku}`).join("; ");
          this.$message.error(`以下项的本次质检量必须大于等于0且不能超过未质检量：${invalidDescriptions}`);
          return;
        }

        // 如果所有项都符合条件，进行提交
        let obj = {
          ordersId: this.exemptOrdersId,
          qualityInspectionData: this.qualityInspectionData
        }
        console.log(JSON.stringify(obj, null, 2));

        const response = await addInspection(obj);
        if (response.code == 200) {
          this.$message.success("操作成功！");
          this.qualityDialogVisible = false;
          this.getList();
        } else {
          this.$message.error("质检提交失败：" + response.data.msg);
        }
      } catch (error) {
        console.error("质检提交异常", error);
      } finally {
        this.loading = false; // 完成加载
      }
    },

    // “免检”按钮点击事件处理
    async handleExemptCheck(row) {

      try {
        this.queryParamProduct.receiptId = row.receiptId; // 存储收货单ID，提交免检时使用
        this.exemptOrdersId = row.ordersId //存储采购订单id用于提交免检时使用
        // 获取收货单详情
        const response = await getReceipt(row.receiptId);

        // 过滤出未质检完成的产品
        const uninspectedProducts = response.data.DTOReceiptProductsList.filter(
          (item) => item.notInspected != 0
        );

        // 如果所有产品都已质检完成，提示用户并停止操作
        if (uninspectedProducts.length === 0) {
          this.$message.warning("收货单中的所有产品已经质检完毕，不能进行免检！");
          return; // 停止后续执行
        }

        // 准备免检数据
        this.exemptInspectionData = response.data.DTOReceiptProductsList.map(item => ({
          receiptNumber: row.receiptNumber,
          imgName: item.imgName,
          productName: item.productName,
          sku: item.sku,
          notInspected: item.notInspected,
          currentInspectionQuantity: null,
          productId: item.productId,
          receiptProductId: item.receiptProductId,
          receiptId: item.receiptId,
          transferableNumber: item.transferableNumber,
          waitingStock: item.waitingStock,
          notifiedCount: item.notifiedCount,
          unnotifiedQuantity: item.unnotifiedQuantity,
          receiptQuantity: item.receiptQuantity,
          pendingQuantity: item.pendingQuantity,
          qualityInspection: item.qualityInspection,
          checkedQuantity: item.checkedQuantity,
          availableQuantity: item.availableQuantity,
          defectiveQuantity: item.defectiveQuantity,
          qualityStatus: item.qualityStatus,
          deleteStatus: item.deleteStatus,
          createTime: item.createTime,
          detailsRemark: item.detailsRemark,
          productProNo: item.productProNo,
          ordersId: item.ordersId,
          id: item.id,
          testNotificationQuantity: item.testNotificationQuantity,
          ordersProductId: item.ordersProductId,
          warehouseId: response.data.warehouseId,
          gtin: item.gtin,
          gtins: item.gtins
        }));

        // 显示免检弹窗
        this.exemptDialogVisible = true;
      } catch (error) {
        // 错误处理
        this.$message.error("获取收货单详情失败，请重试");
        console.error("获取收货单详情出错：", error);
      }
    },
    async submitExemptInspection() {
      this.loading = true; // 开始加载
      try {
        // 过滤出有效的免检数据（本次免检量大于0）
        const validExemptData = this.exemptInspectionData.filter(
          (item) => item.currentInspectionQuantity > 0
        );

        // 如果没有有效的免检数据，提示用户并停止提交
        if (validExemptData.length === 0) {
          this.$message.warning("没有有效的免检数据，请检查输入。");
          return;
        }

        // 校验本次免检量
        const invalidItems = validExemptData.filter((item) => {
          const currentInspectionQuantity = Number(item.currentInspectionQuantity);
          return (
            currentInspectionQuantity < 0 ||
            currentInspectionQuantity > item.notInspected
          );
        });

        // 如果存在不合法的项，提示用户并停止提交
        if (invalidItems.length > 0) {
          const invalidDescriptions = invalidItems
            .map((item) => `品名: ${item.productName}，SKU: ${item.sku}`)
            .join("; ");
          this.$message.error(
            `以下项的本次免检量必须大于等于0且不能超过未质检量：${invalidDescriptions}`
          );
          return;
        }

        // 为每个商品添加免检类型
        validExemptData.forEach(item => {
          item.inspectionType = '2'; // 添加免检类型标识
        });

        // 准备提交的数据
        const submissionData = {
          ordersId: this.exemptOrdersId,
          qualityInspectionData: validExemptData,
        };
        console.log(JSON.stringify(submissionData, null, 2));

        const response = await addInspection(submissionData);
        if (response.code == 200) {
          this.$message.success("操作成功！");
          this.exemptDialogVisible = false;
          this.exemptOrdersId = null; //重置临时使用的采购订单id
          this.getList(); // 刷新收货单列表
        } else {
          this.$message.error("免检提交失败：" + response.msg);
        }
      } catch (error) {
        console.error("免检提交异常", error);
        this.$message.error("系统错误，请稍后重试");
      } finally {
        this.loading = false; // 完成加载
      }
    },

    // 设置所有产品的免检量为未质检量
    setAllExemptQuantities() {
      this.exemptInspectionData.forEach((row) => {
        row.currentInspectionQuantity = row.notInspected;
      });
    },

    /** 收货按钮操作 */
    async handleReceived(row) {
      try {
        // 调用后端验证接口，确保可以继续进行收货
        await someApiCall(row.receiptId);

        // 如果验证通过，继续执行收货逻辑
        this.resetReceive();
        const receiptId = row.receiptId || this.ids;
        const receiptNumber = row.receiptNumber || this.receiptNumber;
        let obj = {};

        const response = await getReceiptQuantity(receiptId);
        this.formReceive = response.data;
        this.formReceive.receiptTime = new Date();
        this.DTOReceiptProductsList = response.data.DTOReceiptProductsList;

        // 查询出除了已入库以外的所有订单
        obj.inboundStatus = 1;
        obj.contract = 2;
        obj.warehouseId = response.data.warehouseId;
        obj.ordersNumber = response.data.ordersNumber;

        const procuredOrdersResponse = await getProcuredOrdersTree(obj);
        this.OrderNumberOptions = procuredOrdersResponse.data;

        this.receiveOpen = true;
        this.receiveTitle = receiptNumber;

      } catch (error) {
        // 捕获错误并显示消息
        // this.$modal.msgWarning(error.message || "验证失败，请重试");
      }
    },
    resetReceive() {
      this.formReceive = {
        receiptId: null,
        receiptNumber: null,
        ordersId: null,
        noticeReceiptQuantity: null,
        receiptQuantity: null,
        consignee: null,
        receiptTime: null,
        receiptStatus: null,
        receiptRemark: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
        warehouseId: null,
        name: null,
        userName: null,
      };
    },
    /** 确认收货按钮 */
    async submitFormReceive() {
      try {
        // 表单验证封装为 Promise，便于使用 await
        const isValid = await new Promise((resolve) => {
          this.$refs["form"].validate((valid) => {
            resolve(valid);
          });
        });

        if (!isValid) return;

        // 验证收货量
        let invalidProducts = this.DTOReceiptProductsList.filter((product) => {
          const receiptQuantity = Number(product.receiptQuantity);
          return receiptQuantity <= 0;
        });

        if (invalidProducts.length > 0) {
          let proNoList = invalidProducts.map((product) => product.productProNo).join(", ");
          this.$modal.msgWarning(`产品编号 ${proNoList} 的收货量必须大于0！`);
          return;
        }

        // 所有验证通过，提交数据
        this.formReceive.DTOReceiptProductsList = this.DTOReceiptProductsList;
        console.log(JSON.stringify(this.formReceive, null, 2))

        await updateReceiptConfirm(this.formReceive);

        this.$modal.msgSuccess("确认收货成功");
        this.receiveOpen = false;
        this.getList();

      } catch (error) {
        // 捕获后端验证错误并提示用户
        // this.$modal.msgWarning(error.message || "收货失败，请核实单据状态");
      }
    },
    // 计算并格式化收货差异
    formatDifference(row) {
      const notificationQty = Number(row.notificationQuantity) || 0;
      const receiptQty = Number(row.receiptQuantity) || 0;
      const difference = receiptQty - notificationQty;

      if (difference > 0) {
        return `+${difference}`; // 超收，显示正数
      } else if (difference < 0) {
        return `${difference}`; // 少收，显示负数
      } else {
        return '0'; // 正常
      }
    },
    // 根据差异值返回对应的颜色
    getDifferenceColor(row) {
      const notificationQty = Number(row.notificationQuantity) || 0;
      const receiptQty = Number(row.receiptQuantity) || 0;
      const difference = receiptQty - notificationQty;

      if (difference > 0) {
        return 'green'; // 超收，绿色
      } else if (difference < 0) {
        return 'red'; // 少收，红色
      } else {
        return 'black'; // 正常，默认颜色
      }
    },

    //选择切换事件
    toggleOrderSelection(row) {
      const index = this.selectedOrdersList.indexOf(row.ordersId);
      if (index === -1) {
        // 不在已选列表中，添加到已选
        this.selectedOrdersList.push(row.ordersId);

        // 手动勾选该行
        this.$refs.tableRef.toggleRowSelection(row, true);
      } else {
        // 在已选列表中，移除
        this.selectedOrdersList.splice(index, 1);

        // 手动取消勾选该行
        this.$refs.tableRef.toggleRowSelection(row, false);
      }
    },
    // 点击批量收货按钮
    handleBatchAdd() {
      this.resetBatchForm();
      this.batchOpen = true;
    },
    // 重置批量收货表单
    resetBatchForm() {
      this.batchForm = {
        warehouseId: null,
        ordersIds: [],
        selectedOrders: [],
      };
      this.selectedOrdersList = [];
    },

    // 重置搜索表单
    resetBatchOrdersForm() {
      // 重置表单数据
      this.batchForm.ordersNumber = '';
      // 如果有其他搜索条件，也需要在这里重置
      // this.batchForm.otherField = '';

      // 重置分页参数（可选）
      this.batchForm.pageNum = 1;
      this.batchForm.pageSize = 10;

      // 重新执行查询，加载默认数据
      this.loadAvailableOrders();
    },
    // 当仓库发生变化时，清空已选择的来源单据号
    onBatchWarehouseChange() {
      this.batchForm.ordersIds = [];
      this.batchForm.selectedOrders = [];
      this.$refs.batchFormRef.validateField('warehouseId');
    },
    // 打开选择来源单据号弹窗
    async openSelectOrdersDialog() {
      this.batchForm.pageSize = 10;
      if (!this.batchForm.warehouseId) {
        this.$message.warning('请先选择收货仓库');
        return;
      }

      this.selectOrdersDialogVisible = true;

      // 异步加载未收货的来源单据号
      await this.loadAvailableOrders();
    },

    // 点击搜索按钮
    listUnreceivedOrders() {
      // 重置分页参数（可选）
      this.batchForm.pageNum = 1;
      this.batchForm.pageSize = 10;
      // 调用加载订单的方法
      this.loadAvailableOrders();
    },
    // 加载未收货的来源单据号
    async loadAvailableOrders() {
      try {
        // 构造请求参数
        const params = {
          pageNum: this.batchForm.pageNum,
          pageSize: this.batchForm.pageSize,
          warehouseId: this.batchForm.warehouseId,
          inboundStatus: 1,
          unreceivedOrdersFlag: 1, // 用于查询未被收货过的采购订单
          ordersNumber: this.batchForm.ordersNumber, // 添加采购单号
        };

        // 调用接口获取数据
        const response = await listUnreceivedOrders(params);

        // 更新订单列表和总数
        this.ProcuredOrdersList = response.rows;
        this.total = response.total;
        this.ProcuredOrdersList.sort((a, b) => {
          const aSelected = this.selectedOrdersList.includes(a.ordersId);
          const bSelected = this.selectedOrdersList.includes(b.ordersId);
          if (aSelected && !bSelected) return -1;
          if (!aSelected && bSelected) return 1;
          return 0;
        });


        // 确保在 DOM 更新后执行后续操作
        // await this.$nextTick();
        const currentSelectedOrdersList = [...this.selectedOrdersList];
        // 同步表格的选中状态
        // this.syncTableSelection();
        this.$nextTick(() => {
          if (this.$refs.tableRef) {
            this.ProcuredOrdersList.forEach((row) => {
              if (currentSelectedOrdersList.some(item => Number(item) === Number(row.ordersId))) {
                this.$refs.tableRef.toggleRowSelection(row, true);
              }
            });
          }
        });


      } catch (error) {
        this.$message.error("加载数据失败，请重试！");
      }
    },


    // 批量收货功能中选择来源单据号中的勾选框触发的事件
    handleSelectionOrdersChange(selectedRows) {
      const currentSelectedIds = selectedRows.map(item => item.ordersId);
      const currentPageIds = this.ProcuredOrdersList.map(item => item.ordersId);

      // 从全局选中列表中移除当前页未选中的订单ID
      this.selectedOrdersList = this.selectedOrdersList.filter(id => !currentPageIds.includes(id));

      // 将当前页选中的订单ID添加到全局选中列表中
      this.selectedOrdersList = [...this.selectedOrdersList, ...currentSelectedIds];
    },


    // 确认选择来源单据号
    confirmSelectOrders() {
      if (this.selectedOrdersList.length === 0) {
        this.$message.warning('请至少选择一个来源单据号');
        return;
      }
      const obj = {
        ordersIds: this.selectedOrdersList
      }

      // 获取选中的订单详情，包含商品信息
      getOrdersDetails(obj).then(response => {
        this.batchForm.selectedOrders = response.data;
        this.batchForm.ordersIds = response.data.map(item => item.ordersId);
        // 选择完成后，手动验证并移除验证提示
        this.$nextTick(() => {
          // 触发验证
          this.$refs.batchFormRef.validateField('ordersIds');
        });
        this.selectOrdersDialogVisible = false;
      });
    },
    // 移除已选的来源单据
    removeSelectedOrder(index) {
      this.batchForm.selectedOrders.splice(index, 1);
      this.batchForm.ordersIds.splice(index, 1);
      this.selectedOrdersList.splice(index, 1)
    },
    // 提交批量收货表单
    submitBatchForm() {
      this.$refs['batchFormRef'].validate(valid => {
        if (valid) {
          this.loading = true;
          // 调用后台接口提交批量收货数据
          batchAddReceipt(this.batchForm.selectedOrders).then(response => {
            if (response.code == 200) {
              this.loading = false;
              this.$message.success('批量收货成功');
              this.batchOpen = false;
              this.getList(); // 重新加载收货单列表
            } else {
              this.loading = false;
              this.$message.error(response.msg);
            }
          });
        }
      });
    },
    // 检查某个SKU组的通知收货量是否超过未通知量
    isNotificationExceedGroup(sku) {
      const skuGroup = this.DTOReceiptProductsList.filter(item => item.sku === sku);

      // 汇总整个SKU组的 waitingStock 和 notifiedCount
      const totalWaitingStock = skuGroup.reduce((sum, item) => sum + item.waitingStock, 0);
      const totalNotifiedCount = skuGroup.reduce((sum, item) => sum + item.notifiedCount, 0);

      // 获取该行的 notificationQuantity 值
      const rowNotificationQuantity = skuGroup.find(item => item.sku === sku).notificationQuantity;

      // 判断是否超出未通知量
      return rowNotificationQuantity > (totalWaitingStock - totalNotifiedCount);
    },
    // ★★ 新增：行合并方法
    tableSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (!this.DTOReceiptProductsList || this.DTOReceiptProductsList.length === 0) {
        return { rowspan: 1, colspan: 1 };
      }
      const group = this.skuGroupInfo[row.sku];  // 根据 sku 分组
      if (!group) {
        return { rowspan: 1, colspan: 1 };
      }

      // 对于 GTIN 列，不进行合并
      if (column.property === 'gtin') {
        return { rowspan: 1, colspan: 1 };
      }

      // 除 GTIN 外的所有列
      if (rowIndex === group.firstIndex) {
        // 当前行是该 sku 分组的第一行，显示合并后的单元格
        return { rowspan: group.count, colspan: 1 };
      } else {
        // 当前行不是分组第一行，则隐藏该单元格
        return { rowspan: 0, colspan: 0 };
      }
    },
    /**
      * 用于行合并的回调，在 <el-table> 上用 :span-method="skuSpanMethodDetails"
      * 除了 GTIN 列外，都对同一 SKU 进行合并。
      */
    skuSpanMethodDetails({ row, column, rowIndex }) {
      // // 如果分组信息里找不到 row.sku，直接返回默认
      // if (!this.skuGroupsDetails[row.sku]) {
      //   return { rowspan: 1, colspan: 1 };
      // }
      // // GTIN 列不合并
      // if (column.property === 'gtin') {
      //   return { rowspan: 1, colspan: 1 };
      // }
      // // 其余列合并
      // const group = this.skuGroupsDetails[row.sku];
      // // 如果是分组首行，则行高为 group.count；否则隐藏
      // if (rowIndex === group.firstIndex) {
      //   return { rowspan: group.count, colspan: 1 };
      // } else {
      //   return { rowspan: 0, colspan: 0 };
      // }

      if (!this.OrdersProductListDetails || this.OrdersProductListDetails.length === 0) {
        return { rowspan: 1, colspan: 1 };
      }
      const group = this.skuGroupsDetails[row.sku];  // 根据 sku 分组
      if (!group) {
        return { rowspan: 1, colspan: 1 };
      }

      // 对于 GTIN 列，不进行合并
      if (column.property === 'gtin') {
        return { rowspan: 1, colspan: 1 };
      }

      // 除 GTIN 外的所有列
      if (rowIndex === group.firstIndex) {
        // 当前行是该 sku 分组的第一行，显示合并后的单元格
        return { rowspan: group.count, colspan: 1 };
      } else {
        // 当前行不是分组第一行，则隐藏该单元格
        return { rowspan: 0, colspan: 0 };
      }
    },
    handleSelect(selection, row) {
      const group = this.skuGroupsDetails[row.sku];
      if (!group) return;

      // 当前是选中还是取消
      const checked = selection.some(r => r.id === row.id);

      // 开始批量切换：屏蔽 selection-change
      this.isBulkSelecting = true;

      // 批量切换行的选中状态
      group.rows.forEach(r => {
        this.$refs.myTable.toggleRowSelection(r, checked);
      });

      // 批量切换结束，等 DOM 更新后再恢复并手动更新一次 idss
      this.$nextTick(() => {
        this.isBulkSelecting = false;
        // 手动把当前所有被选中的行的 id 同步到 idss
        const allSelected = this.$refs.myTable.selection || [];
        this.handleSelectionChangeOrdersId(allSelected);
      });
    },
    /**
     * 全选操作：选择该 SKU 组下所有项
     * @param {Array} selection 当前全选的行
     */
    handleSelectAll(selection) {
      const allSelected = selection || [];

      // 获取所有 SKU 分组
      const skuGroups = Object.keys(this.skuGroupsDetails);

      // 遍历每个 SKU 分组并确保每个分组的所有项都被勾选
      skuGroups.forEach(sku => {
        const group = this.skuGroupsDetails[sku];
        if (group) {
          group.rows.forEach(row => {
            if (!allSelected.some(item => item.id === row.id)) {
              allSelected.push(row);  // 把所有属于该 SKU 分组的行加进去
            }
          });
        }
      });

      // 更新选中项
      this.handleSelectionChangeOrdersId(allSelected);
    },
    /**
      * 单行勾选/取消：把同 SKU 的整组行都批量切换到同样状态
      *
      * @param {Array}  selection 当前已选中行列表（Element 2.x 版本）
      * @param {Object} row       刚被点击的那一行
      */
    handleReceiptProductSelect(selection, row) {
      // 1. 找出同 sku 的所有行
      const sku = row.sku;
      const groupRows = this.DTOReceiptProductsList.filter(item => item.sku === sku);

      // 2. 判断本次操作是勾选还是取消
      //    （Element 2.x：selection 中有没有 row；3.x 则是直接第二个参数 selected=true/false）
      const checked = selection.some(r => r === row);

      // 3. 屏蔽中间的 selection-change
      this.isBulkSelectingReceipt = true;

      // 4. 批量切换同组行
      groupRows.forEach(r => {
        this.$refs.DTOReceiptProducts.toggleRowSelection(r, checked);
      });

      // 5. 等 DOM 更新完，再恢复，并手动同步一次 selection-change
      this.$nextTick(() => {
        this.isBulkSelectingReceipt = false;
        this.handleReceiptProductsSelectionChange(this.$refs.DTOReceiptProducts.selection);
      });
    },
  },
};
</script>

<style>
.el-input--small .el-input__inner {
  height: 36px;
  line-height: 32px;
}

.text-ellipsis {
  overflow: hidden;
  /* 隐藏超出部分的文本 */
  white-space: nowrap;
  /* 文本不换行 */
  text-overflow: ellipsis;
  /* 显示省略符号 */
}
</style>
